const { AjaxGet } = require('../../request/request')
// pages/lineList/lineList.js
const api = require('../../request/request')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin:0,
    id:"",//当前用户id
    yuyue:false,
    quxiao:false,
    timer:null,
    list:[],
    status:null,
    Detail:"",//温馨提示
    text:"",
  },
  getUserProfile(e) {
    let self = this
    if(self.data.isLogin==1){
      clearInterval(self.data.timer)
      wx.navigateTo({
        url: '../submit/submit',
      })
    }else{
       // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        wx.setStorageSync('wechatUrl', res.userInfo.avatarUrl)
        wx.setStorageSync('wechatName', res.userInfo.nickName)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        self.login()
      }
    })
    }
   
  },
  login(){
    wx.showLoading({title: '加载中…'})
    wx.login({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        var that = this;
        if(res.code){
          let url ="/talks_record/getWXOpenid?jsCode=" + res.code
          api.AjaxGet(url,(res)=>{
            console.log(res)
            if(res.code=="10000"){
              var openid = res.data.openid
                wx.setStorageSync('tel', openid) //储存openid
                wx.setStorageSync('status', "0")
                // setTimeout(()=>{
                 this.setData({
                   isLogin:1
                 })
                wx.hideLoading()
                // },1500)
            }else{
              wx.showToast({
                title: res.message,
                icon: 'none',
                duration: 2000
              })
            }
            })
          // wx.request({
          //   url: '',
          //   data:{
          //     appid:"wx311db324b43462d2",
          //     secret:'3aa5450f372c9a5e6b3841a5bd4850aa',
          //     grant_type: 'authorization_code',
          //     js_code: res.code
          //   },
          //   method: 'GET',
          //   success:(res)=>{
          //     console.log(res)
          //       var openid = res.openid
          //       wx.setStorageSync('tel', openid) //储存openid
          //       wx.setStorageSync('status', "0")
          //       setTimeout(()=>{
          //         clearInterval(that.data.timer)
          //         wx.hideLoading()
          //         wx.navigateTo({
          //           url: '../submit/submit',
          //         })
          //       },1500)

          //   },
          //   fail:(err)=>{
          //     console.log('用户拒绝授权')
          //   }

          // })
        }

      },
      fail:(err)=>{
        wx.hideLoading()
      }
    })

  },
  getDetail(){
    let url = "/text_detail/selectByType?type=1"
    api.AjaxGet(url,(res)=>{
      console.log(res)
      if(res.code=="10000"){
        // this.data.list = res.data.data
        this.setData({
          Detail:res.data.indexDetail
        })
      }else{
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })
      }
         
      })
  },
  getList(){
    // let params={
    //   pageNum:1,
    //   pageSize:100
    // }
    let tel = wx.getStorageSync('tel')
    let status = wx.getStorageSync('status')
    let departmentId = wx.getStorageSync('departmentId')
    let myDate = new Date();
    let year = myDate.getFullYear();
    let month = myDate.getMonth() + 1;
    if(month<10){
      month="0"+month
    }
    this.setData({
      text:""
    })
    let day = myDate.getDate();
    if(day<10){
      day="0"+day
    }
    let beginTime =year+"-"+month+"-"+day+" "+"00:00:00"
    let url
    if(departmentId){
       url ="/talks_record/selectList?pageNum=1&pageSize=100&beginTime="+ beginTime +"&departmentId=" + departmentId
    }else{
      url ="/talks_record/selectList?pageNum=1&pageSize=100&beginTime="+ beginTime +"&departmentId=3" 
    }
    api.AjaxGet(url,(res)=>{
    console.log(res)
    if(res.code=="10000"){
      // this.data.list = res.data.data
      let list =[]
      if(status==0){
        this.setData({
          yuyue:true,
          quxiao:false,
        })
      }else if(status==1){
        this.setData({
          yuyue:false,
          quxiao:false,
        })
      }
   
      res.data.data.forEach((el,i,arr) => {
        if(el.telReal==tel&&status==0){//当前用户显示开始或者结束按钮
          console.log('222')
          this.setData({
            id:el.id,
            yuyue:false,
            quxiao:true,
          })
          if(i+1==1){
            this.setData({
              text:"您目前处于队列中第"+(i+1)+"位,请进入会谈"
            })
          }else{
            if(i+1==2||i+1==3||i+1==4){
              this.setData({
                text:"您目前处于队列中第"+(i+1)+"位,请进入等待区"
              })
            }else{
              this.setData({
                text:"当前共有"+ (arr.length) +"人排队，您目前处于队列中第"+(i+1)+"位,请耐心排队"
              })
            }
           
          }
          //当前用户显示开始按钮
          if(i+1==1&&(el.recordStatus==1||el.recordStatus==5)){
            el.beginBtn=1;
          }
          //当前用户显示等待按钮
          if((i+1==2||i+1==3||i+1==4)&&el.recordStatus==1){
            el.wait = 1
          }else if(i+1!==1&&el.recordStatus==1){
            el.line=1
          }else if((i+1==2||i+1==3||i+1==4)&&el.recordStatus==5){
            el.loading=1
          }
          //当前用户显示结束按钮
          if(i+1==1&&el.recordStatus==2){
            el.endBtn=1;
          }
        }else if(status==0&&el.telReal!==tel){//其他用户显示排队
          console.log('111')
          if(i+1==1&&el.recordStatus==2){
            // this.setData({beginBtn:1})
            el.start=1;
            // el.endBtn=0;
            // list.push(el)
          }else if(i==2||i==3||i==4){
            //其他用户等待
          el.line = 1;
          // list.push(el)
          }else{
            el.line = 1;
          }
          
        }
        if(status==1){//医生只显示结束
          // el.beginBtn=0;
          el.endBtn=1;
          // list.push(el)
        }
          list.push(el)
      });
      console.log(list)
      this.setData({
        list:list,
        status:status
      })
    }else{
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }
    })
  },
  waitPop(e){
    let _this = this
    wx.showModal({
      title: '提示',
      content: '确认等待',
      success (res) {
        if (res.confirm) {
          _this.wait(e)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  wait(e){
    console.log(e.target.dataset.item)
    let myDate = new Date();
    let year = myDate.getFullYear();
    let month = myDate.getMonth() + 1;
    if(month<10){
      month="0"+month
    }
    let day = myDate.getDate();
    if(day<10){
      day="0"+day
    }
    let beginTime =year+"-"+month+"-"+day+" "+"00:00:00"
    let id = e.target.dataset.item.id;
    let params={
      id:id,
      beginTime:beginTime,
      recordStatus:5
    }
    console.log(params)
    let url ="/talks_record/begin_wait_record"
      api.AjaxPost(url,params,(res)=>{
        console.log(res)
        if(res.code=="10000"){
          // this.data.list = res.data.data
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
          this.getList()
        }else{
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
        }
        })
  },
  beginPop(e){
    let _this = this
    wx.showModal({
      title: '提示',
      content: '确认开始',
      success (res) {
        if (res.confirm) {
          _this.begin(e)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  begin(e){
    console.log(e.target.dataset.item)
    let myDate = new Date();
    let year = myDate.getFullYear();
    let month = myDate.getMonth() + 1;
    if(month<10){
      month="0"+month
    }
    let day = myDate.getDate();
    if(day<10){
      day="0"+day
    }
    let beginTime =year+"-"+month+"-"+day+" "+"00:00:00"
    let id = e.target.dataset.item.id;
    let params={
      id:id,
      beginTime:beginTime,
      recordStatus:1
    }
    console.log(params)
    let url ="/talks_record/begin_record"
      api.AjaxPost(url,params,(res)=>{
        console.log(res)
        if(res.code=="10000"){
          // this.data.list = res.data.data
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
          this.getList()
        }else{
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
        }
        })
  },
  endPop(){
    let _this = this
    wx.showModal({
      title: '提示',
      content: '每天可以预约三次，确认取消？',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          _this.end()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  jieshuPop(e){
    let _this = this
    wx.showModal({
      title: '提示',
      content: '确认结束？',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          _this.jieshu(e)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  jieshu(e){
    let status = wx.getStorageSync('status')
    let id = e.target.dataset.item.id;
    let params={
      id:id,
    }
    console.log(params)
    //0:访客结束；1：医生结束
    let url;
    if(status==0){
       url ="/talks_record/end_record"
    }else{
       url ="/talks_record/doctor_end_record"
    }
      api.AjaxPost(url,params,(res)=>{
        console.log(res)
        if(res.code=="10000"){
          // this.data.list = res.data.data
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
          this.getList()
        }else{
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
        }
        })
  },
  end(){
    let status = wx.getStorageSync('status')
    let id = this.data.id;
    let params={
      id:id,
    }
    console.log(params)
    //0:访客结束；1：医生结束
    let url;
    if(status==0){
       url ="/talks_record/cancel_wait_record"
    }
      api.AjaxPost(url,params,(res)=>{
        console.log(res)
        if(res.code=="10000"){
          // this.data.list = res.data.data
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
          this.getList()
        }else{
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })
        }
        })
  },
  goSubmit(){
    let _this =this
    let tel = wx.getStorageSync('tel')
    if(tel){
      clearInterval(_this.data.timer)
      wx.navigateTo({
        url: '../submit/submit',
      })
    }else{
      wx.showModal({
        title: '登录后才能预约排队',
        content: '是否登录？',
        success (res) {
          if (res.confirm) {
            clearInterval(_this.data.timer)
            wx.navigateTo({
              url: '../login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  
  },
   //登录
  // login(){
  //   let _this = this
  //   wx.showModal({
  //     title: '尚未登录',
  //     content: '是否登录？',
  //     success (res) {
  //       if (res.confirm) {
  //         clearInterval(_this.data.timer)
  //         wx.navigateTo({
  //           url: '../login/login',
  //         })
  //       } else if (res.cancel) {
  //         console.log('用户点击取消')
  //       }
  //     }
  //   })
  // },
  //登出
  loginOut(){
    let _this = this
    wx.showModal({
      title: '提示',
      content: '是否退出登录？',
      success (res) {
        if (res.confirm) {
          // clearInterval(_this.data.timer)
          wx.removeStorageSync('tel')
          _this.setData({
            isLogin:false
          })
          _this.getList()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   wx.removeStorageSync('tel')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let tel = wx.getStorageSync('tel')
    if(tel.length>0){
     this.setData({
      isLogin:1
     })
    }else{
      this.setData({
        isLogin:0
       })
    }
    this.getDetail()
    this.getList()
    this.data.timer = setInterval(()=>{
      this.getList()
    },10000)
    console.log(this.data.timer)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log(this.data.timer)
    clearInterval(this.data.timer)
    wx.removeStorageSync('tel')
    this.setData({
      timer:null
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})